var app = getApp();
var request = app.request;
var setting = app.globalData.setting;
var common = require('../../../utils/common.js');
import Regions from '../../../utils/regions/Regions.js';
Page({
  data: {
    url: setting.url,
    store: {
      shop_images: []
    },
    region: ['广东省', '广州市', '海珠区'],
    address: {}, //收货地址信息
    status: -1,
    reason: ''
  },

  onLoad: function (options) {
    if(options.phone) {
      this.setData({
        ['store.shop_phone']: options.phone,
        ['store.shop_id']: options.shop_id
      })
    }
    console.log(options.shop_id)
    console.log(typeof options.shop_id)
    if(options.shop_id && options.shop_id != 'null') {
      this.requestDetail();
    }
    this.initRegions();
  },
  // 开门时间
  bindTimeChange(e) {
    this.setData({
      ['store.work_end_time']: e.detail.value
    })
    console.log(this.data, 1)
  },
  // 开门时间
  bindTimeChange1(e) {
    console.log(e, 2)
    this.setData({
      ['store.work_start_time']: e.detail.value
    })
  },
  // 删除当前图片
  deleteImg(e) {
    let list = [...this.data.store.shop_images]
    list.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      'store.shop_images': list
    });
  },
  /** 初始化区域弹框相关 */
  initRegions: function () {
    var that = this;
    new Regions(this, 'regions', {
      endAreaLevel: 3,
      endAreaLevelCall: function (parentId, regionName, address) {
        Object.assign(that.data.address, address);
        that.setData({
          'address.province_name': that.data.address.province_name,
          'address.city_name': that.data.address.city_name,
          'address.district_name': that.data.address.district_name,
          'store.province_id': that.data.address.province,
          'store.city_id': that.data.address.city,
          'store.district_id': that.data.address.district
        });
      }
    });
  },
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value,
      'store.province_id': e.detail.value[0],
      'store.city_id': e.detail.value[1],
      'store.district_id': e.detail.value[2],
    })
  },
  // 获取当前经纬度
  lalo() {
    let that = this
    wx.getLocation({
      isHighAccuracy: true,
      success(res) {
        console.log(res)
        that.setData({
          'store.longitude': res.longitude,
          'store.latitude': res.latitude,
        });
      }
    })
  },
  requestDetail: function () {
    var that = this;
    request.get('/api/shop/detail', {
      data: {
        shop_id: this.data.store.shop_id
      },
      success: function (res) {
        that.setData({
          status: res.data.data.apply_status || -1,
          reason: res.data.data.reject_reason || ''
        })
        if(res.data.status == 0) {
          return;
        }
        // let imglist = []
        // res.data.result.shop_images.forEach(e => {
        //   imglist.push(e.image_url)
        // })

        // let awlist = {
        //   province_name: res.data.result.region_address.split(' ')[0],
        //   city_name: res.data.result.region_address.split(' ')[1],
        //   district_name: res.data.result.region_address.split(' ')[2]
        // }
        res.data.data.shop_info.shop_images = [res.data.data.shop_info.shop_image]
        that.setData({
          store: res.data.data.shop_info,
          // address: awlist
        });
        that.initRegions();
      },
      failStatus: function () {
        return false;
      }
    });
  },
  requestMyStore: function () {
    var that = this;
    request.get('/api/shop/getShopInfo', {
      success: function (res) {
        let imglist = []
        res.data.result.shop_images.forEach(e => {
          imglist.push(e.image_url)
        })

        let awlist = {
          province_name: res.data.result.region_address.split(' ')[0],
          city_name: res.data.result.region_address.split(' ')[1],
          district_name: res.data.result.region_address.split(' ')[2]
        }
        res.data.result.shop_images = imglist
        that.setData({
          store: res.data.result,
          address: awlist
        });
        that.initRegions();
      },
      failStatus: function () {
        return false;
      }
    });
  },

  submitStore: function (e) {
    var that = this;
    var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    var data = Object.assign(e.detail.value, {
      province_id: this.data.store.province_id,
      city_id: this.data.store.city_id,
      // shop_pic: this.data.store.shop_pic,
      district_id: this.data.store.district_id,
      shop_image: this.data.store.shop_images,
      work_start_time: this.data.store.work_start_time,
      work_end_time: this.data.store.work_end_time,
      // shop_desc:  this.data.store.shop_desc,
      shop_phone: this.data.store.shop_phone,
    });
    console.log(data, e)
    if (data.shop_name.replace(/\s+/g, '') == "") {
      return app.showTextWarining("请输入自提点名称");
    } else if (data.shop_address.replace(/\s+/g, '') == "") {
      return app.showTextWarining("请输入自提点地址");
    }
    //  else if (data.shop_phone.replace(/\s+/g, '') == "") {
    // 	return app.showTextWarining("请输入手机号");
    // } else if (!myreg.test(data.shop_phone)) {
    // 	return app.showTextWarining("手机号不合法");
    // } 
    else if (data.province_id == 0 || data.province_id == '') {
      return app.showTextWarining("请选择地址");
    }

    request.post('/api/shop/apply', {
      data: data,
      success: function (res) {
        if (res.data.status == 1) {
          app.showSuccess(res.data.msg);
          that.setData({
            ['store.shop_id']: res.data.data.shop_id,
            status: res.data.data.audit_status
          })
          // setTimeout(that.requestDetail(), 3000);
          // that.requestMyStore();
        }
      }
    });
    // request.post('/api/distribut/store', {
    //     data: data,
    //     success: function (res) {
    //         app.showSuccess(res.data.msg);
    //         that.setData({ store: res.data.result });
    //         wx.navigateBack();
    //     }
    // });
  },

  changeStoreImg: function (e) {
    var that = this;
    wx.chooseImage({
      count: 1, //最多1张图片,默认9
      sizeType: ['compressed', 'original'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['camera', 'album'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        request.uploadFile('/api/distribut/upload_store_img', {
          filePath: res.tempFilePaths[0],
          name: 'store_img',
          success: function (res) {
            let list = [...that.data.store.shop_images]
            if (e.currentTarget.dataset.index) {
              list[e.currentTarget.dataset.index] = res.data.result
            } else {
              list.push(res.data.result)
            }
            that.setData({
              'store.shop_images': list
            });
          }
        });
      }
    });
  },
  changeStorePic: function () {
    var that = this;
    wx.chooseImage({
      count: 1, //最多1张图片,默认9
      sizeType: ['compressed', 'original'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['camera', 'album'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        request.uploadFile('/api/distribut/upload_store_pic', {
          filePath: res.tempFilePaths[0],
          name: 'store_pic',
          success: function (res) {
            that.setData({
              'store.shop_pic': res.data.result
            });
          }
        });
      }
    });
  },
  // 弹出核销验证码弹窗
  showCodeModel(){
    var that = this;
    wx.showModal({
      title: '请输入核销码',
      editable: true,
      placeholderText: '请输入核销码',
      success (res) {
        if (res.confirm) {
          if(res.content) {
            var data = {};
            if(res.content.length > 9) {
              data["order_sn"] = res.content
            } else {
              data["bar_code"] = res.content
            }
            request.get('/api/order/pickup_detail', {
              data: data,
              success: function (res2) {
                if(res2.data.status == 0) {
                  app.showTextWarining(res2.data.msg);
                } else {
                  wx.navigateTo({
                    url: '/pages/user/order_detail/order_detail?type=1&order_id=' + res2.data.data.order_info.order_id+'&code='+res.content+'&shop_id='+that.data.store.shop_id
                  });
                }
              }
            });
          } else {
            app.showTextWarining("核销码不能为空");
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
})